import React, { useRef, useEffect } from 'react';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { drawPolyline } from './drawFn';
import { splitPolyline } from './helper';

/**
 *
 * @param {object} layerCfg graphic layer
 * @param {function} getView 返回view的函数
 * @returns
 */
function useDrawPolyline(layerCfg = {}, getView = void 0) {
  const GraphicRef = useRef(null);
  const layerRef = useRef(null);
  const viewRef = useRef(null);

  useEffect(() => {
    init();
    return () => {};
  }, []);

  async function init() {
    const [GraphicsLayer, Graphic] = await jsapi.load([
      'esri/layers/GraphicsLayer',
      'esri/Graphic',
    ]);
    GraphicRef.current = Graphic;
    viewRef.current = await viewUtils.isViewReady(getView);
    // 复用已挂载layer
    if (layerCfg.id) {
      layerRef.current = viewRef.current.map && viewRef.current.map.findLayerById(layerCfg.id);
    }
    if (!layerRef.current) {
      layerRef.current = new GraphicsLayer({
        elevationInfo: {
          mode: 'relative-to-scene',
        },
        ...layerCfg,
      });
    }
    // 用于比对
    updatePolylineGraphic.layer = layerRef.current;
    viewRef.current.map.add(layerRef.current);
  }

  function createPolylineGraphic(symbol, color) {
    if (!GraphicRef.current) {
      console.error('graphic初始化失败');
      return Promise.reject();
    }
    const graphic = new GraphicRef.current({ symbol });

    return drawPolyline(
      { graphic, layer: layerRef.current, view: viewRef.current },
      true,
      color,
    ).then(polyline => {
      console.log(polyline, '-------');
      return splitPolyline(polyline, graphic);
    });

    // .then(() => {
    //   return graphic;
    // });
  }

  function updatePolylineGraphic(graphic) {
    console.log('update updatePolylineGraphic');
    return drawPolyline(
      { graphic, layer: layerRef.current, view: viewRef.current },
      false,
      graphic.symbol.color.toHex(),
    ).then(() => [graphic]);
  }

  return [createPolylineGraphic, updatePolylineGraphic];
}

export default useDrawPolyline;
